import { types, getEnv, getSnapshot, applySnapshot, flow } from "mobx-state-tree";
import { User } from "./User";
import { Project } from "./App";
import { reaction } from "mobx";

export const MainStore = types
    .model("MainStore", {
        user: types.optional(User, {}),
        project: types.array(Project),
    })
    .views(self => ({
    }))
    .actions(self => {
        function toggleAsideFolded() {
            self.asideFolded = !self.asideFolded;
            sessionStorage.setItem("asideFolded", self.asideFolded ? "1" : "");
        }
        return {
            toggleAsideFolded,
            setStatus: function (status) {
                self.status = status;
            },
            afterCreate: function () {
                // persist store
                if (typeof window !== "undefined" && window.sessionStorage) {
                    const storeData = window.sessionStorage.getItem("store");
                    if (storeData) applySnapshot(self, JSON.parse(storeData));

                    reaction(
                        () => getSnapshot(self),
                        json => {
                            window.sessionStorage.setItem("store", JSON.stringify(json));
                        },
                    );
                }
            },
            beforeDestroy() {},
        };
    });
